package com.monika.main.system.util.doc;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author:whh
 * @date: 2025-05-10 14:08
 * <p>
 *     PDF处理器可分页加载PDF
 *
 * </p>
 */
public class PDF  extends Document<PdfDocument,byte[]> {


    /**
     * 总页数
     */
    private int pages;


    /**
     * 当前页
     */
    private int cur = 1;


    public PDF(File pdf) throws IOException {
        super(new PdfDocument(new PdfReader(pdf)));
        this.pages = doc.getNumberOfPages();
    }

    /**
     * 返回PDF中的某一页
     *
     * @param page
     * @return
     */
    public byte[] PDFPage(int page) {
        if (page <= 0) {
            throw new RuntimeException("起始页必须大于0");
        }
        if (page > pages) {
            page = pages;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // 验证页码范围（这里省略了验证逻辑，应该添加检查以确保startPage <= endPage <= totalPages）
        PdfWriter writer = new PdfWriter(out);
        PdfDocument dstDoc = new PdfDocument(writer);
        doc.copyPagesTo(page, page, dstDoc);
        dstDoc.close();
        return out.toByteArray();
    }


    @Override
    public boolean hasNext() {
        return cur <= pages;
    }

    public byte[] next() {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // 验证页码范围（这里省略了验证逻辑，应该添加检查以确保startPage <= endPage <= totalPages）
        PdfWriter writer = new PdfWriter(out);
        PdfDocument dstDoc = new PdfDocument(writer);
        doc.copyPagesTo(cur, cur, dstDoc);
        dstDoc.close();
        cur++;
        return out.toByteArray();
    }


    public static void main(String[] args) throws IOException {
        File file = new File("doc/1.pdf");

        System.out.println(file.getPath());
        try ( PDF ff = new PDF(file);) {
            while (ff.hasNext()) {
                System.out.println(Arrays.toString(ff.next()));
            }

        } catch (Exception ex) {
        }

    }

}
